package com.futer.ssm.util;

import com.alibaba.fastjson.JSONObject;
import com.futer.ssm.model.User;
import com.futer.ssm.model.UserExample;
import com.futer.ssm.service.Service;
import com.futer.ssm.service.UserService;

import javax.servlet.http.HttpSession;
import java.util.List;

public class CheckNameAndEmail {

    public static String checkNameAndEmailInfo(User user, Service userService, HttpSession session){
        //检查用户修改的名字和email是否合法，不合法不允许修改

        //检查名字,存在name则返回-30，表示不允许修改
        UserExample name = new UserExample();
        UserExample.Criteria criteriaName = name.createCriteria();
        criteriaName.andNameEqualTo(user.getName());
        List<User> usersName = userService.getUser(name);

        System.out.println((user.getId()+","+usersName.get(0).getId()));

        if (usersName.size()>1){
            return JSONObject.toJSONString(-30);
        }else if (usersName.size() == 1){
            if (usersName.get(0).getId() != user.getId()){
                return JSONObject.toJSONString(-30);
            }else {
                return JSONObject.toJSONString(0);
            }
        }


        if ( !((User)(session.getAttribute("user"))).getEmail().equals(user.getEmail())){
            //检查email,存在email则返回-20，表示不允许修改
            UserExample ue = new UserExample();
            UserExample.Criteria criteria = ue.createCriteria();
            criteria.andEmailEqualTo(user.getEmail());
            List<User> users = userService.getUser(ue);
            if (users.size()!=0){
                return JSONObject.toJSONString(-20);
            }
        }

        return  JSONObject.toJSONString(0);

    }
}
